package com.binhthuan.catechist.server.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.binhthuan.catechist.server.ErrorObject;
import com.binhthuan.catechist.server.ResponseObject;
import com.binhthuan.catechist.server.bus.ShiftBUS;
import com.binhthuan.catechist.server.domain.Shift;
import com.binhthuan.catechist.shared.constant.Parameter;

public class ShiftServlet extends AbstractServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        addShift(request, response);
    }

    @Override
    protected void fetch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter(Parameter.ID) == null) {
            getAllShifts(request, response);
        } else {
            getShiftById(request, response);
        }
    }

    @Override
    protected void remove(HttpServletRequest request, HttpServletResponse response, boolean confirmation) throws ServletException,
            IOException {
        removeShift(request, response);
    }

    @Override
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        updateShift(request, response);
    }

    private void addShift(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter(Parameter.NAME);
        String dayOfWeek = request.getParameter(Parameter.DAY_OF_WEEK);
        String startTimeString = request.getParameter(Parameter.START_TIME);
        String endTimeString = request.getParameter(Parameter.END_TIME);

        try {
            java.util.Date startTime = dateTimeFormatter.parse(startTimeString);
            java.util.Date endTime = dateTimeFormatter.parse(endTimeString);

            if (startTime.compareTo(endTime) >= 0) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.END_TIME, getMessagesFactory().invalidTimeRange());
                sendResponse(error.toJson());
                return;
            }

            ShiftBUS shiftBUS = new ShiftBUS();

            if (shiftBUS.getShiftByName(name.trim()) != null) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().shiftIsDuplicated());
                sendResponse(error.toJson());
                return;
            }

            Shift newShift = new Shift();
            newShift.setName(name.trim());
            newShift.setDayOfWeek(dayOfWeek.trim());
            newShift.setStartTime(startTime);
            newShift.setEndTime(endTime);

            if (shiftBUS.save(newShift)) {
                sendResponse(new ResponseObject(newShift).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getAllShifts(HttpServletRequest request, HttpServletResponse response) {
        ShiftBUS shiftBus = new ShiftBUS();
        List<Shift> shifts = shiftBus.getAllShifts();

        sendResponse(new ResponseObject(shifts).toJson());
    }

    private void getShiftById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter(Parameter.ID);
        try {
            int shiftId = Integer.parseInt(id);
            ShiftBUS shiftBus = new ShiftBUS();
            Shift shift = shiftBus.getShiftById(shiftId);
            sendResponse(new ResponseObject(shift).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void removeShift(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String shiftId = request.getParameter(Parameter.ID);

        try {
            int id = Integer.parseInt(shiftId);

            ShiftBUS shiftBus = new ShiftBUS();
            if (shiftBus.isInUsed(id)) {
               ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
               error.addError(Parameter.NAME, getMessagesFactory().shiftIsInUsed());
               sendResponse(error.toJson());
               return;
            }

            if (shiftBus.deleteShift(id)) {
                sendResponse(new ResponseObject((Object) null).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void updateShift(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String shiftId = request.getParameter(Parameter.ID);
        String name = request.getParameter(Parameter.NAME);
        String dayOfWeek = request.getParameter(Parameter.DAY_OF_WEEK);
        String startTimeString = request.getParameter(Parameter.START_TIME);
        String endTimeString = request.getParameter(Parameter.END_TIME);

        try {
            int id = Integer.parseInt(shiftId);
            java.util.Date startTime = dateTimeFormatter.parse(startTimeString);
            java.util.Date endTime = dateTimeFormatter.parse(endTimeString);

            if (startTime.compareTo(endTime) >= 0) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.END_TIME, getMessagesFactory().invalidTimeRange());
                sendResponse(error.toJson());
                return;
            }

            ShiftBUS shiftBus = new ShiftBUS();
            Shift shift = shiftBus.getShiftByName(name.trim());

            if (shift != null && shift.getId() != id) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().shiftIsDuplicated());
                sendResponse(error.toJson());
                return;
            }

            shift = shiftBus.getShiftById(id);
            shift.setName(name.trim());
            shift.setDayOfWeek(dayOfWeek.trim());
            shift.setStartTime(startTime);
            shift.setEndTime(endTime);

            if (shiftBus.save(shift)) {
                sendResponse(new ResponseObject(shift).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}
